from rest_framework import viewsets, status
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.views.decorators.csrf import csrf_exempt
import logging
from ..serializers import EventSerializer
from ..services.conflict_service import ConflictService

logger = logging.getLogger('apps')


class BaseResponse:
    """基础响应类"""

    @staticmethod
    def success(data=None, message="操作成功"):
        return Response({
            "status": "success",
            "message": message,
            "data": data
        })

    @staticmethod
    def error(message="操作失败", status=status.HTTP_400_BAD_REQUEST):
        return Response({
            "status": "error",
            "message": message
        }, status=status)


@csrf_exempt
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def batch_create_events(request):
    """批量创建日程"""
    try:
        events_data = request.data.get('events', [])
        # 新增参数：是否忽略内部冲突
        ignore_conflicts = request.data.get('ignore_conflicts', False)
        ignore_internal_conflicts = request.data.get('ignore_internal_conflicts', False)

        if not events_data:
            return Response({
                "status": "error",
                "message": "请提供日程数据"
            }, status=status.HTTP_400_BAD_REQUEST)

        logger.info(f"开始批量创建日程，数量: {len(events_data)}")

        # 先检测冲突
        if not ignore_conflicts:
            conflict_service = ConflictService()
            conflict_result = conflict_service.check_conflicts(request.user, events_data)

            # 如果存在冲突且不忽略冲突，则返回冲突信息
            if conflict_result['has_conflicts']:
                # 检查是否只有内部冲突且忽略内部冲突
                has_external_conflicts = conflict_result.get('has_external_conflicts', True)
                has_internal_conflicts = conflict_result.get('has_internal_conflicts', False)

                # 如果只有内部冲突且设置了忽略内部冲突，则继续创建
                if has_internal_conflicts and not has_external_conflicts and ignore_internal_conflicts:
                    logger.info("只有内部冲突且设置了忽略内部冲突，继续创建")
                else:
                    return Response({
                        "status": "conflict",
                        "message": f"检测到 {conflict_result['conflict_count']} 个日程冲突",
                        "data": conflict_result
                    }, status=status.HTTP_409_CONFLICT)

        # 继续执行原有的批量创建逻辑
        created_events = []
        errors = []

        for index, event_data in enumerate(events_data):
            try:
                logger.debug(f"处理第 {index + 1} 个日程: {event_data}")

                # 验证必要字段
                required_fields = ['title', 'date', 'start_time', 'end_time']
                missing_fields = [field for field in required_fields if not event_data.get(field)]
                if missing_fields:
                    error_msg = f"缺少必要字段: {', '.join(missing_fields)}"
                    logger.warning(f"日程 {index + 1} {error_msg}")
                    errors.append({
                        'index': index,
                        'error': error_msg
                    })
                    continue

                # 处理时间段
                try:
                    start_hour = int(event_data['start_time'].split(':')[0])
                    period = 'morning' if start_hour < 12 else 'afternoon'
                except (ValueError, IndexError):
                    period = 'morning'
                    logger.warning(f"日程 {index + 1} 时间格式错误，默认设置为上午")

                # 构建完整的日程数据
                full_event_data = {
                    'title': event_data['title'],
                    'date': event_data['date'],
                    'start_time': event_data['start_time'],
                    'end_time': event_data['end_time'],
                    'description': event_data.get('description', ''),
                    'location': event_data.get('location', ''),
                    'importance': event_data.get('importance', 'medium'),
                    'status': 'pending',
                    'period': period,
                    'related_note_id': event_data.get('related_note_id'),  # 添加关联笔记ID
                }

                # 记录关联笔记ID
                related_note_id = event_data.get('related_note_id')
                if related_note_id:
                    logger.info(f"日程 {index + 1} 关联笔记ID: {related_note_id}")

                # 创建序列化器并传入上下文
                serializer = EventSerializer(
                    data=full_event_data,
                    context={'request': request}
                )

                if serializer.is_valid():
                    # 保存日程，显式设置用户和创建者
                    event = serializer.save(
                        user=request.user,
                        creator_id=request.user.id,
                        from_note=bool(event_data.get('related_note_id')),  # 如果有关联笔记ID，则设置from_note为True
                        related_note_id=related_note_id  # 确保related_note_id被正确设置
                    )
                    # 添加创建者为相关用户
                    event.related_users.add(request.user)
                    created_events.append(serializer.data)
                    logger.info(f"日程 {index + 1} 创建成功: {event.title}")
                else:
                    error_msg = f"数据验证失败: {serializer.errors}"
                    logger.warning(f"日程 {index + 1} {error_msg}")
                    errors.append({
                        'index': index,
                        'error': error_msg
                    })
            except Exception as e:
                error_msg = f"处理失败: {str(e)}"
                logger.error(f"日程 {index + 1} {error_msg}")
                errors.append({
                    'index': index,
                    'error': error_msg
                })

        # 确定响应状态
        if len(created_events) > 0:
            response_status = 'success' if not errors else 'partial_success'
            http_status = status.HTTP_200_OK if not errors else status.HTTP_207_MULTI_STATUS
            logger.info(f"批量创建完成: 成功 {len(created_events)}, 失败 {len(errors)}")
        else:
            response_status = 'error'
            http_status = status.HTTP_400_BAD_REQUEST
            logger.warning("批量创建失败: 所有日程创建都失败了")

        response_data = {
            'status': response_status,
            'message': f"批量创建完成: 成功 {len(created_events)} 个, 失败 {len(errors)} 个",
            'data': {
                'created_events': created_events,
                'created_count': len(created_events),
                'failed_count': len(errors),
                'errors': errors if errors else None
            }
        }

        return Response(response_data, status=http_status)

    except Exception as e:
        error_msg = f"批量创建日程发生错误: {str(e)}"
        logger.error(error_msg)
        return Response({
            'status': 'error',
            'message': error_msg
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)